// pages/dispatch/dispatch.ts
import { getSystemInfoSync } from '../../utils/util'
var url = require("../../utils/urls");
var commons = require("../../utils/common");
var tip = require("../../utils/tip");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showDropdown: false, // 是否展示下拉列表 押运员
    showDropdownDir: false, // 是否展示下拉列表 司机
    showDropdownTra:false, // 是否展示下拉列表 挂车
    escortInfoId:'',//押运员id
    escortInfoName:'',//押运员姓名
    driverId:'',//司机id
    guaName:'',//司机姓名
    guaPhone:'',//司机电话
    trailerNumber:'',//挂车牌号
    escortInfoType:'',//押运类型
    supercargo:[],
    planResVOS:[],
    isShowSupercargo:true,//危货/普货
    radioList: [
      { label: '押运', value: 0, checked:true},
      { label: '双驾', value: 1, checked:false},
    ],
    options: [],// 所有选项 押运员
    filteredOptions: <any>[],  // 过滤后的选项 押运员
    optionsDir: [],// 所有选项 司机
    filteredOptionsDir: <any>[],  // 过滤后的选项 司机
    optionsTra: [],// 所有选项 挂车牌号
    filteredOptionsTra: <any>[],  // 过滤后的选项 挂车牌号
    selectedRadio: 'option1',  // 默认选中的单选框项
    systemInfo: {},
    list: [],
    carNumber: "",
    tonnage: "",
    show: false,
    item: {},
    planItem: {},
    current: 1,
    size: 10,
    totalPage: 0,
    isSMSNotification:0,
    checked:false,
  },
  radioChange: function(e) {
    console.log(e.currentTarget.dataset.index,'select')
    console.log(e.detail.value,'e.detail.value')
    const selectedValue = e.detail.value;
    const radioList = this.data.radioList;
    radioList.forEach(item => {
      item.checked = item.value === selectedValue;
    });
    let indexr = e.currentTarget.dataset.index
    const yyType = e.detail.value;
    this.setData({
      radioList: radioList,
      escortInfoType: selectedValue,
      [`list[${indexr}].yyType`] : yyType
    });
  },
  // 输入框输入事件 押运员
  onSearchInput(event:any) {
       console.log(event.currentTarget.dataset.index,'event')
       const keyword = event.detail.value;
       const trimValue = keyword.replace(/\s+/g, '');
       if(keyword !== ''){
        console.log('押运员')
         // 模拟根据关键字过滤选项数据的逻辑
          const filtered = this.data.options.filter(item => item.name.includes(trimValue));
          console.log(filtered,'filtered')
          const indexh = event.currentTarget.dataset.index;
          const speName = filtered[0]?.name
          this.setData({  
            showDropdown: true,
            filteredOptions: filtered,                            
            [`list[${indexh}].speName`] : speName
          });
       }
  },
   // 输入框输入事件 司机
   onSearchInputDriver(event:any) {
    console.log(event.currentTarget.dataset.index,'event')
    const keyword = event.detail.value;
    const trimValue = keyword.replace(/\s+/g, '');
    if(keyword !== ''){
      let requestUrl = url.listIdleDriverInfo
      let obj = {
        "driverName": keyword
      }
        commons.get(requestUrl,obj).then(res=>{
          console.log(res,'sdaf')
          if (res.code == 200) {
            let resData = res.data
            console.log(resData,'空闲司机')
            this.setData({
              optionsDir: resData
            })  
            // 模拟根据关键字过滤选项数据的逻辑
            const filtered = this.data.optionsDir.filter(item => item.driverName.includes(trimValue));
            console.log(filtered,'filtered')
            const indexsj = event.currentTarget.dataset.index;
            const dirName = filtered[0]?.driverName
            this.setData({  
              showDropdownDir: true,
              filteredOptionsDir: filtered,                            
              [`list[${indexsj}].dirName`] : dirName
            });
          } else {
            tip.showToast(res.msg, 'error', 1000)
          }
        })
    }
},
 // 输入框输入事件 挂车牌号
 onSearchInputTra(event:any) {
  console.log(event.currentTarget.dataset.index,'event')
    const keyword = event.detail.value;
    const trimValue = keyword.replace(/\s+/g, '');
    if(keyword !== ''){
      let requestUrl = url.listTrailerVehicleInfo
      let obj = {
        "trailerCarNumber": keyword
      }
        commons.get(requestUrl,obj).then(res=>{
          console.log(res,'sdaf')
          if (res.code == 200) {
            let resData = res.data
            console.log(resData,'空闲挂车')
            this.setData({
              optionsTra: resData
            })  
            // 模拟根据关键字过滤选项数据的逻辑
            const filtered = this.data.optionsTra.filter(item => item.trailerCarNumber.includes(trimValue));
            console.log(filtered,'filtered')
            const indexsj = event.currentTarget.dataset.index;
            const traNumber = filtered[0]?.trailerCarNumber
            this.setData({  
              showDropdownTra: true,
              filteredOptionsTra: filtered,                            
              [`list[${indexsj}].traNumber`] : traNumber
            });
          } else {
            tip.showToast(res.msg, 'error', 1000)
          }
        })
    }
},
  // 下拉框选项点击事件 押运员
  onDropdownItemSelected(event:any) {
    console.log(event.currentTarget.dataset,'index')
    const escortName = event.currentTarget.dataset.name
    const escortInfoId = event.currentTarget.dataset.id
    const indexp = event.currentTarget.dataset.index
    this.setData({
      showDropdown: false, 
      filteredOptions: [],
      [`list[${indexp}].escortName`] : escortName,
      escortInfoId: escortInfoId,
      escortInfoName: escortName
    });
  },
    // 下拉框选项点击事件 司机
  onDropdownItemSelectedDriver(event:any){
    console.log(event.currentTarget.dataset,'index')
    const dirName = event.currentTarget.dataset.name
    const dirPhone = event.currentTarget.dataset.phone
    const driverId = event.currentTarget.dataset.id
    const indexsiji = event.currentTarget.dataset.index
    this.setData({
      showDropdownDir: false, 
      filteredOptionsDir: [],
      [`list[${indexsiji}].guaName`] : dirName,
      [`list[${indexsiji}].guaPhone`] : dirPhone,
      driverId: driverId,
      guaName: dirName,
      guaPhone: dirPhone
    });
  },
     // 下拉框选项点击事件 挂车牌号
     onDropdownItemSelectedTra(event:any){
      console.log(event.currentTarget.dataset.id,'index')
      const id = event.currentTarget.dataset.id
      const indexgc = event.currentTarget.dataset.index
      this.setData({
        showDropdownTra: false, 
        filteredOptionsTra: [],
        [`list[${indexgc}].trailerNumber`] : id,
        trailerNumber: id
      });
    },
  dispatch(e) {
    this.setData({
      show: true,
      tonnage: "",
      item: e.currentTarget.dataset.item,
    })
  },
  //短信通知单选按钮
  checked(e){    
    console.log(e.currentTarget.dataset.index,'e')
    let item = e.currentTarget.dataset.index
    this.setData({
      [`list[${item}].checked`] : this.data.checked == true?this.data.checked = false:this.data.checked = true
    });
     this.data.checked === false ?this.data.isSMSNotification = 0 : this.data.isSMSNotification = 1
    },
  cancel() {
    this.setData({
      show: false,
    })
  },
  dispatchSure: async function () {
    if (!this.data.tonnage) {
      tip.showToast('请输入装车净重', 'error', 1000)
      return
    } else {
      if (this.data.tonnage > 99) {
        tip.showToast('吨数不能超出99', 'error', 1000)
        return
      }
    }
    let requestUrl = url.savePlanDispatch
    let item = this.data.item
    console.log(this.data.escortInfoType)
    let json = {
      "carNumber": item.carNumber,
      "trailerCarNumber":this.data.trailerNumber,//挂车车牌号
      "userId": this.data.driverId?this.data.driverId:item.driverId,
      "driverName": this.data.guaName?this.data.guaName:item.driverName,//司机姓名
      "driverPhone": this.data.guaPhone?this.data.guaPhone:item.driverPhone,//司机电话
      "planId": this.data.planItem.id?this.data.planItem.id:'-1',
      "tonnage": this.data.tonnage,
      "isSMSNotification":this.data.isSMSNotification,
      "escortInfoId": this.data.escortInfoId,
      "escortInfoName": this.data.escortInfoName,
      "escortInfoType": this.data.escortInfoType,
      "planResVOS": this.data.planResVOS
    }
    let data = await commons.postJson(requestUrl, json);
    if (data.code == 200) {
      tip.showToast(data.msg, 'success', 1000)
      this.idleVehicle(this.data.carNumber, 1)
      this.setData({
        show: false
      })
    } else {
      tip.showToast(data.msg, 'error', 1000)
      this.setData({
        show: false
      })
    }
  },
  tonnageInput(e) {
    this.setData({
      tonnage: e.detail.value
    })
  },
  carNumberInput(e) {
    this.setData({
      current: 1,
      carNumber: e.detail.value
    })
    this.idleVehicle(this.data.carNumber,this.data.current)
  },
  allListEscortInfo: async function () {
    let requestUrl = url.allListEscortInfo
    let data = await commons.get(requestUrl);
    console.log(data,'sdfs')
    if (data.code == 200) {
      let resData = data.data
      console.log(resData,'空闲押运员')
      this.setData({
        options: resData
      })  
    } else {
      tip.showToast(data.msg, 'error', 1000)
    }
  },
  allListEscortInfoTra: async function (keyword) {
    let requestUrl = url.listTrailerVehicleInfo
    let obj = {
      "trailerCarNumber": keyword
    }
    let data = await commons.get(requestUrl,obj);
    if (data.code == 200) {
      let resData = data.data
      console.log(resData,'空闲挂车牌号')
      this.setData({
        optionsTra: resData
      })  
    } else {
      tip.showToast(data.msg, 'error', 1000)
    }
  },
  idleVehicle: async function (carNumber, current) {
    if (current == 1) {
      this.setData({
        list: [],
        current: current
      })
    }
    let requestUrl = url.idleVehicle
    let json = {
      current: this.data.current,
      size: this.data.size,
      "carNumber": carNumber
    }
    let data = await commons.postJson(requestUrl, json);
    if (data.code == 200) {
      let resData = data.data
      console.log(resData,'resData.records')
      for(let item of resData.records){
        item.escortName = '';//押运员
        item.guaName = '';//司机
        item.guaPhone = '';//司机电话
        item.speName = '';//押运员
        item.dirName = '';//司机
        item.traNumber = '';//挂车牌号
        item.trailerCarNumber = '';//挂车牌号
        item.yyType = ''
        item.checked = ''
       }
      this.setData({
        list: this.data.list.concat(resData.records),
        totalPage: Math.ceil(resData.total / this.data.size)
      })
     
      // console.log(resData.records,'resData.records')
  
    } else {
      tip.showToast(data.msg, 'error', 1000)
    }
  },

  loadMore(e) {
    console.log('加载更多')
    if (this.data.totalPage === 1) {
      return
    }

    if (this.data.current < this.data.totalPage) {
      this.setData({
        current: this.data.current + 1,
      })
      this.idleVehicle()
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(e) {
    console.log(e,'ererererere')
    let systemInfo = getSystemInfoSync()
    this.setData({
      systemInfo: systemInfo
    })
    if(e.array){
      let receivedArray = JSON.parse(e.array);
      this.data.planResVOS = receivedArray
      this.idleVehicle()
      this.allListEscortInfo()
    }
    if(e.item){
      let a = JSON.parse(e.item)
      if(a.goodsTransportedType == 1){
        this.setData({
          planItem:JSON.parse(e.item)
        })
        this.idleVehicle()
        this.allListEscortInfo()
      }else{
        // console.log('普货')
        this.setData({
          planItem:JSON.parse(e.item),
          isShowSupercargo: false
        })
        this.idleVehicle()
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      current: 1,
      list: []
    })
    this.idleVehicle()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})